package springmvc.utils;

import springmvc.utils.parseImpl.DoubleParseString;
import springmvc.utils.parseImpl.IntegerParseString;
import springmvc.utils.parseImpl.LongParseString;
import springmvc.utils.parseImpl.StringParseString;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author cg
 * @date 2023/6/17 14:25
 */
public class ParseStringContext{
    private static Map<Class<?>, ParseString> parseStringMap;
    static {
        parseStringMap = new ConcurrentHashMap<>();
        parseStringMap.put(String.class, new StringParseString());
        parseStringMap.put(Long.class, new LongParseString());
        parseStringMap.put(long.class, new LongParseString());
        parseStringMap.put(Double.class, new DoubleParseString());
        parseStringMap.put(double.class, new DoubleParseString());
        parseStringMap.put(Integer.class, new IntegerParseString());
        parseStringMap.put(int.class, new IntegerParseString());
    }
    private ParseStringContext(){};

    public static Object parse(Class<?> clazz,String value) {
        ParseString parseString = parseStringMap.get(clazz);
        if (parseString != null) return parseString.parse(value);
        else return null;
    }

    /**
     * 通过反射给自定义的类自动填充属性值
     * @param clazz 自定义类
     * @param requestBodyMap 请求参数列表
     * @return
     */
    public static Object objectParseString(Class<?> clazz, Map<String, String> requestBodyMap) {
        Object instance = null;
        try {
            instance = clazz.getConstructor().newInstance();
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                String value = requestBodyMap.get(fieldName);
                if (value != null&&!"".equals(value)){
                    field.set(instance, parse(field.getType(), value));
                }
            }
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            throw new RuntimeException(e + "参数转换失败");
        }
        return instance;
    }

}
